package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.MyResponseResult;
import com.itheima.utils.MyJwtUtil;
import com.itheima.utils.MyThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

//@WebFilter("/*")
//@Component
public class MyLoginFilter implements Filter {

    //@Autowired
    private MyJwtUtil myJwtUtil;
    //这个方法在每次浏览器请求的时候都会执行一次
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest  request= (HttpServletRequest)servletRequest;
        String uri = request.getRequestURI();
        if ("/login".equals(uri)){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
//            走完登陆的资源之后，没有必要走下面关于校验令牌的代码了，因此可以使用return提前结束这个过滤器
            return;
        }

        //Token检验的
        String token = request.getHeader("Token");
        Map<String, Object>map = myJwtUtil.parseJwt(token);

            //不合法情况
            if (map==null){
                MyResponseResult<Object> error = MyResponseResult.error("NOT_LOGIN");
                //error响应给前端（需要把对象转json由于目前代码没有执行controller，因此需要我们自己手动转成json并手动响应数据）
                String jsonString = JSONObject.toJSONString((error));
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.getWriter().println(jsonString);
                return;
            }

            //合法的情况，用threadlocal  本地线程保存一个变量以便于后续的使用
           MyThreadLocalUtil.setValue(map);
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
    }
}
